package com.kk.controller;

import com.kk.entity.RbacManager;
import com.kk.entity.ResponseEntity;
import com.kk.service.RbacManagerService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/rbacManager")
public class RbacManagerController {
    private  ApplicationContext context;
    private RbacManagerService rbacManagerServiceImpl;
    {
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        rbacManagerServiceImpl = context.getBean("rbacManagerServiceImpl", RbacManagerService.class);

    }
    @RequestMapping("/addUser")
    public ResponseEntity addUser(@RequestBody @Valid RbacManager rbacManager, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            String msg = fieldError.getDefaultMessage();
            return new ResponseEntity<>(500,msg,null);
        }else {
            int i = rbacManagerServiceImpl.addOne(rbacManager);
            if(i > 0){
                return new ResponseEntity<>(200,"添加成功",null);
            }else {
                return new ResponseEntity<>(500,"添加数据失败",null);
            }
        }

    }
    @RequestMapping("/findOneById")
    public ResponseEntity findOneById(int id){
        RbacManagerService rbacManagerServiceImpl = context.getBean("rbacManagerServiceImpl", RbacManagerService.class);
        RbacManager oneById = rbacManagerServiceImpl.findOneById(id);
        if(oneById != null){
            return new ResponseEntity<>(200,"成功找到用户",oneById);
        }else {
            return new ResponseEntity<>(500,"没有找到用户",null);
        }
    }

    @RequestMapping("deleteUser")
    public ResponseEntity deleteUser(int id){
        int i = rbacManagerServiceImpl.deleteById(id);
        if(i > 0){
            return new ResponseEntity<>(200,"删除成功",null);
        }else {
            return new ResponseEntity<>(500,"删除失败",null);
        }
    }
}
